from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from ..models import Department, UserInfo, PrettyNum, Admin
from django import forms
from django.forms import Form, ModelForm
from django.utils.safestring import mark_safe
from ..utils.pagination import Pagination
from ..utils.bootstrap import BootStrapModelForm
from ..utils.form import UserModelForm, PrettynumModelForm, PrettynumEditModelForm, AdminModelForm, AdminEditModelForm, AdminResetModelForm
from ..utils.code import check_code
from ..utils.encrypt import md5
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from io import BytesIO

class LoginForm(forms.Form):
    username = forms.CharField(label='用户名', widget=forms.TextInput(attrs={'class': 'form-control'}), required=True)
    password = forms.CharField(label='密码', widget=forms.PasswordInput(render_value=True,attrs={'class': 'form-control'}), required=True)
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'class': 'form-control'}), required=True)

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")
        if user_input_code.upper() != code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})
        admin_object = Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error('password', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        request.session['info'] = {'name': admin_object.username, 'id': admin_object.id}  # session把当前登录的名字存储在浏览器
        request.session.set_expiry(60 * 60 * 24 * 7)  # session可以保存7天
        return redirect('/admin/list/')
    return render(request, 'login.html', {'form': form})

def logout(request):
    request.session.clear()  # 把当前用户session清除掉
    return redirect('/login/')

def image_code(request):
    img, code_string = check_code()
    request.session['image_code'] = code_string  # 写入到浏览器session中
    request.session.set_expiry(60)  # 超时
    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())